package com.google.zxing.journeyapps.barcodescanner;

import com.google.zxing.ResourceTable;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.multimodalinput.event.KeyEvent;
import ohos.utils.PacMap;

public class CaptureActivity extends Ability implements BusHelper.Observable {
    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);

        WindowManager windowManager = WindowManager.getInstance();
        Window window = windowManager.getTopWindow().get();
        window.setTransparent(true);

        barcodeScannerView = initializeContent();
        capture = new CaptureManager(this, barcodeScannerView);
        capture.initializeFromIntent(getIntent(), null);
        BusHelper.getINSTANCE().register("CameraPreviewStarted",this);
    }

    /**
     * Override to use a different layout.
     *
     * @return the DecoratedBarcodeView
     */
    protected DecoratedBarcodeView initializeContent() {
        setUIContent(ResourceTable.Layout_zxing_capture);
        return (DecoratedBarcodeView)findComponentById(ResourceTable.Id_zxing_barcode_scanner);
    }

    @Override
    protected void onActive() {
        super.onActive();
        capture.onResume();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        capture.onPause();
    }

    @Override
    protected void onStop() {
        capture.onDestroy();
        BusHelper.getINSTANCE().unRegister(this);
        super.onStop();
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        capture.onSaveInstanceState(outState);
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        capture.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return barcodeScannerView.onKeyEvent(barcodeScannerView, event) || super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSubscribe(Object object) {
        if (capture != null)
            capture.decode();
    }
}
